﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using ProjectMercury.Emitters;
using ProjectMercury;
using ProjectMercury.Renderers;
using Microsoft.Xna.Framework.Graphics;
using UnitLibrary.GameObjects.UnitReaders;

namespace UnitLibrary.Managers
{
    public class ParticleEffectsM: Manager, IManager
    {
        private Dictionary<string, Emitter> _particleEffects;
        private SpriteBatchRenderer _renderer;
        private Matrix _camera = new Matrix();
        
        public ParticleEffectsM(Game game, ComponentM components)
            : base(game, components)
        {
            _particleEffects = new Dictionary<string, Emitter>();
            _renderer = new SpriteBatchRenderer { BlendMode = SpriteBlendMode.AlphaBlend };
            
            List<string> _particleEffectNames = ObjectSerialization<List<string>>.DeserializeLocation("D:\\Saeculum\\AttackTest\\Content\\ProjectMercury\\ParticleEffectsList");
            Emitter particleEffect;
            foreach (string name in _particleEffectNames)
            {
                particleEffect = ObjectSerialization<Emitter>.Deserialize(name);
                _particleEffects.Add(name, particleEffect);
            }
        }

        public void Initialize()
        {
            foreach (KeyValuePair<string, Emitter> effect in _particleEffects)
            {
                effect.Value.Initialise();
            }
        }

        public void LoadContent()
        {
            this.Initialize();
            foreach (KeyValuePair<string, Emitter> effect in _particleEffects)
            {
                effect.Value.LoadContent(this._game.Content);                
            }
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            _renderer.Batch = spriteBatch;
            foreach (KeyValuePair<string, Emitter> effect in _particleEffects)
            {
                _renderer.RenderEmitter(effect.Value, ref _camera);
            }
        }

        public void Update(GameTime gameTime)
        {
            _camera = _components.cameraManager.CameraMatrix;
            foreach (KeyValuePair<string, Emitter> effect in _particleEffects)
            {
                effect.Value.Update((float)gameTime.TotalGameTime.TotalSeconds, (float)gameTime.ElapsedGameTime.TotalSeconds);
            }
        }

        public void TriggerEmitter(string emitterName, Vector2 position)
        {
            Emitter _emitter;
            _particleEffects.TryGetValue(emitterName, out _emitter);
            if (_emitter != null)
                _emitter.Trigger(position);
            else
                Console.WriteLine("Couldn't trigger emitter: " + emitterName);
        }
    }
}
